#!/usr/bin/env python
# -*- coding:utf8 -*-
# uncompyle6 version 2.15.1
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.10 (default, Jul  1 2017, 13:36:56) 
# [GCC 4.4.6 20110731 (Red Hat 4.4.6-4)]
# Embedded file name: ./esb/components/generic/apis/cmsi/toolkit/send_mail_with_smtp.py
# Compiled at: 2017-11-16 15:44:28
"""
Tencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
"""
import smtplib, mimetypes
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.utils import COMMASPACE
from common.base_utils import smart_str
from common.bkerrors import bk_error_codes
from common.log import logger

class SMTPClient(object):

    def __init__(self, smtp_host, smtp_port, smtp_user='', smtp_pwd='', smtp_usessl=False, smtp_timeout=10):
        self.smtp_host = smtp_host
        self.smtp_port = smtp_port
        self.smtp_user = smtp_user
        self.smtp_pwd = smtp_pwd
        self.smtp_usessl = smtp_usessl
        self.smtp_timeout = smtp_timeout

    def send_mail(self, kwargs):
        mail_sender = kwargs['sender']
        all_receiver = kwargs['receiver'] + kwargs['cc']
        msg = MIMEMultipart()
        msg['Subject'] = smart_str(kwargs['title'])
        msg['From'] = mail_sender
        msg['To'] = COMMASPACE.join(kwargs['receiver'])
        msg['Cc'] = COMMASPACE.join(kwargs['cc'])
        self.add_content_to_msg(msg, kwargs['content'], kwargs.get('body_format'))
        try:
            smtp = self.get_smtp_client()
            smtp.sendmail(mail_sender, all_receiver, msg.as_string())
            smtp.quit()
        except:
            logger.exception('%s send mail exception, server: %s:%s', bk_error_codes.REQUEST_SMTP_ERROR.code, self.smtp_host, self.smtp_port)
            return {'result': False,'message': u'邮件发送失败。'}

        return {'result': True,'message': u'邮件发送成功。'}

    def add_content_to_msg(self, mail_msg, content, body_format):
        body_format = 'plain' if body_format == 'Text' else 'html'
        msgtxt = MIMEText(smart_str(content), body_format, 'utf-8')
        mail_msg.attach(msgtxt)

    def add_attachment_to_msg(self, mail_msg, attachment):
        """
        :param attachment:
        [
            {
                'file_name': 'test.jpg',   # 文件名
                'file_content': 'xxx',     # 文件内容
                'file_type': 'image',      # 文件类型
            }
        ]
        """
        for file_info in attachment:
            file_name = file_info['file_name']
            file_content = file_info['file_content']
            file_type = file_name.split('.')['-1'] or file_info.get('file_type', 'attachment')
            if file_type in ('image', 'jpg', 'png', 'jpeg'):
                att = MIMEImage(file_content)
                att.add_header('Content-ID', '<%s>' % file_name)
                mail_msg.attach(att)
            else:
                ctype, encoding = mimetypes.guess_type(file_name)
                if ctype is None or encoding is not None:
                    ctype = 'application/octet-stream'
                maintype, subtype = ctype.split('/', 1)
                att = MIMEImage(file_content, _subtype=subtype)
                att.add_header('Content-Disposition', 'attachment', filename=file_name)
                mail_msg.attach(att)

        return

    def get_smtp_client(self):
        if self.smtp_usessl:
            smtp = smtplib.SMTP_SSL(self.smtp_host, self.smtp_port, timeout=self.smtp_timeout)
        else:
            smtp = smtplib.SMTP(self.smtp_host, self.smtp_port, timeout=self.smtp_timeout)
        if self.smtp_user and self.smtp_pwd:
            smtp.login(self.smtp_user, self.smtp_pwd)
        return smtp
